﻿using ApiLib.AppStart;
using ApiLib.Utils;
using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.AspNetCore.Http;

namespace ApiLib.Common.Filters;

/// <summary>
/// 默认中间件
/// </summary>
public class DefaultMiddleware
{
    private readonly RequestDelegate _next;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="next"></param>
    public DefaultMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public async Task InvokeAsync(HttpContext context)
    {
        // ...
        if (context.Request.Headers.ContainsKey(CorsConstants.Origin))
        {
            try
            {
                context.Response.Headers.AccessControlAllowOrigin = "*";
                context.Response.Headers.AccessControlAllowHeaders = context.Request.Headers.AccessControlAllowHeaders;
                context.Response.Headers.AccessControlAllowMethods = "PUT,POST,GET,DELETE,OPTIONS,HEAD,PATCH";
                context.Response.Headers.AccessControlAllowCredentials = "true";
                if (context.Request.Method.Equals("OPTIONS"))
                {
                    await _next(context);
                    return;
                }
            }
            catch (Exception e)
            {
                WebUtil.LogExp(e.Message);
            }
        }
        var path = context.Request.Path.Value;
        var isProd = GlobalConfig.AppConfig?.IsProd ?? false;
        if (isProd && path != null && path.StartsWith("/swagger/"))
        {
            // context.Response.Body.Write(Encoding.Default.GetBytes("<h1>禁止访问</h1>"));
            await context.Response.WriteAsync("<h1>禁止访问</h1>");
            // context.Response.Redirect("../404.html");
            return;
        }

        // 调用下一个中间件
        await _next(context);
    }
}